<template>
    <div v-loading="loading" loading-tip="正在保存中，请勿刷新页面">
        <a-modal
            title="设置模板"
            centered
            v-model:visible="visible"
            :width="1000"
            :bodyStyle="{ height: '600px', overflow: 'auto' }"
            okText="保存"
            @ok="handleSave"
            @cancel="handleCancel"
        >
            <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                <a-row>
                    <a-col :span="10">
                        <a-form-item label="模板名称" name="name">
                            <a-input v-model:value="form.name" allowClear :maxlength="33" placeholder="请输入" />
                        </a-form-item>
                    </a-col>
                    <a-col :span="10">
                        <a-form-item label="模板类型" name="type">
                            <a-select placeholder="请选择" allowClear v-model:value="form.type">
                                <a-select-option key="1"> 双周迭代会 </a-select-option>
                                <a-select-option key="2"> 其他 </a-select-option>
                            </a-select>
                        </a-form-item>
                    </a-col>
                </a-row>

                <a-row>
                    <a-col :span="24">
                        <h-section title="选择飞书多维表格" collapse>
                            <a-row>
                                <a-col :span="13">
                                    <a-form-item label="飞书文档" name="fsFileName">
                                        <div>
                                            <HSearchSelectCell
                                                :show-arrow="true"
                                                :default-value="form.fsFileName"
                                                type="fsFileName"
                                                label="title"
                                                keyField="docs_token"
                                                allowClear
                                                @success="handleSelectChange($event, 'fsFileName')"
                                            >
                                            </HSearchSelectCell>
                                        </div>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="13">
                                    <a-form-item label="选择数据表" name="fsTableName">
                                        <a-select
                                            :disabled="!form.fsFileName"
                                            placeholder="请选择"
                                            v-model:value="form.fsTableName"
                                            @change="handleSelectChange($event, 'fsTableName')"
                                        >
                                            <a-select-option v-for="item of fsTableOptions" :key="item.name">
                                                {{ item.name }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </h-section>
                    </a-col>
                </a-row>

                <a-row>
                    <a-col :span="24">
                        <h-section title="选择同步数据的所属系统" collapse>
                            <a-row>
                                <a-col :span="12">
                                    <a-form-item label="选择数据源系统" name="catalogCode">
                                        <div>
                                            <HSearchSelectCell
                                                :show-arrow="true"
                                                :default-value="form.catalogCode"
                                                type="platformSystem"
                                                :searchQuery="{ catalogType: 1 }"
                                                label="systemName"
                                                keyField="catalogCode"
                                                allowClear
                                                @success="handleSelectChange($event, 'catalogCode')"
                                            />
                                        </div>
                                    </a-form-item>
                                </a-col>
                            </a-row>
                        </h-section>
                    </a-col>
                </a-row>

                <a-row>
                    <a-col :span="24">
                        <h-section collapse>
                            <template #title>
                                <div>
                                    <span>设置同步需求数据的字段</span>
                                    <span class="caption-font-color" style="font-weight: 400">
                                        （请确保字段名与表格列名相同，同步后列名会自动锁定）</span
                                    >
                                </div>
                            </template>
                            <a-row>
                                <a-col :span="12">
                                    <a-table size="small" bordered :columns="fieldColumns" :dataSource="fieldList" :pagination="false">
                                        <template #checked="{ record }">
                                            <a-checkbox :disabled="record.title === '产品需求编号'" v-model:checked="record.checked"> </a-checkbox>
                                        </template>
                                    </a-table>
                                </a-col>
                            </a-row>
                        </h-section>
                    </a-col>
                </a-row>
            </a-form>
        </a-modal>
    </div>
</template>

<script lang="ts">
import api from '@/api';
import { useMessage } from '@/hooks/common/useMessage';
import { HSearchSelectCell } from '@/components';
import { SmileOutlined } from '@ant-design/icons-vue';
import { DownOutlined, UpOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue/es';
import { defineComponent, ref, unref, reactive, toRefs, nextTick } from 'vue';
export default defineComponent({
    components: {
        DownOutlined,
        UpOutlined,
        HSearchSelectCell,
        SmileOutlined
    },
    emits: ['success'],
    setup(_, { emit }) {
        const { createConfirm } = useMessage();
        const ruleFormRef = ref<any>();
        const validateRepeatName = async (rule: any, value: any) => {
            if (value) {
                const query = {
                    tempName: state.form.tempName,
                    id: state.form.id,
                    fsAccountId: state.info.id
                };
                const { success } = await api.feishuModel.validFieldRepeat(query, { cancelDuplicated: true });
                return success ? Promise.reject('模板名称不能相同') : Promise.resolve();
            }
        };
        const rules = {
            name: [
                { required: true, message: '模板名称不能为空', trigger: 'blur' },
                { required: true, validator: validateRepeatName }
            ],
            fsFileName: [{ required: true, message: '飞书文档不能为空', trigger: 'blur' }],
            fsTableName: [{ required: true, message: '数据表不能为空', trigger: 'blur' }],
            catalogCode: [{ required: true, message: '数据源系统不能为空', trigger: 'blur' }]
        };
        const state = reactive<any>({
            visible: false,
            fsTableOptions: [],
            detail: {},
            info: {},
            form: {
                name: '',
                type: null,
                fsFileName: '',
                fsTableName: '',
                id: null,
                fieldList: '',
                catalogCode: '',
                fsFileToken: '',
                fsTableId: ''
            },
            fieldList: [
                { title: '所属产品', checked: true },
                { title: '产品需求编号', checked: true },
                { title: '产品需求名称', checked: true },
                { title: '产品需求描述', checked: false },
                { title: '产品负责人', checked: false },
                { title: '需求类型', checked: true },
                { title: '优先级', checked: true },
                { title: '预发布版本号', checked: true },
                { title: '预计交付时间', checked: false },
                { title: '预计开始时间', checked: false },
                { title: '预估工时', checked: false },
                { title: '前端预估工时', checked: true },
                { title: '后端预估工时', checked: true },
                { title: '前端实际工时', checked: true },
                { title: '后端实际工时', checked: true },
                { title: '关联业务需求', checked: true },
                { title: '状态', checked: true },
                { title: '冲刺', checked: true },
                { title: '研发负责人', checked: false }
            ],
            fieldColumns: [
                {
                    title: 'PMP字段',
                    dataIndex: 'title',
                    align: 'center'
                },
                {
                    title: '',
                    dataIndex: 'checked',
                    align: 'center',
                    slots: { customRender: 'checked' }
                }
            ],
            loading: false
        });
        const resetForm = () => {
            state.form = {
                name: '',
                type: null,
                fsFileName: '',
                fsTableName: '',
                id: null,
                fieldList: '',
                catalogCode: '',
                fsFileToken: '',
                fsTableId: ''
            };
        };
        const open = (detail = {}) => {
            state.visible = true;
            state.detail = { ...detail };
            nextTick(() => {
                unref(ruleFormRef).clearValidate();
            });
            if (state.detail.id) {
                Object.keys(state.form).forEach((key) => {
                    state.form[key] = state.detail[key];
                });
                // 获取数据表选项
                if (state.form.fsFileName && state.form.fsFileToken) {
                    getFsTableOptions();
                }
                let { fieldList } = state.detail;
                if (fieldList) {
                    fieldList = fieldList.split(',');
                    state.fieldList.forEach((item, index) => {
                        if (fieldList.includes(item.title)) {
                            state.fieldList[index].checked = true;
                        } else {
                            state.fieldList[index].checked = false;
                        }
                    });
                }
            } else {
                resetForm();
            }
        };
        const handleSave = () => {
            unref(ruleFormRef)
                .validate()
                .then(async () => {
                    state.loading = true;
                    const fieldList: any = [];
                    state.fieldList.forEach((item) => {
                        if (item.checked) {
                            fieldList.push(item.title);
                        }
                    });
                    const query = {
                        ...state.form,
                        fieldList: fieldList.join(',')
                    };
                    const { success, errorCode } = await api.fsFileSyncTmplModel.save(query);
                    if (success) {
                        message.success(state.form.id ? '修改成功' : '新增成功');
                        emit('success');
                        handleCancel();
                    } else {
                        if (errorCode == 12) {
                            createConfirm({
                                title: '提示',
                                content: '已经存在一个数据源系统、目标多维表格、目标多维表格数据表完全相同的模板，无需新增。',
                                iconType: 'warning',
                                okText: '确定',
                                keyboard: false,
                                cancelButtonProps: { style: { display: 'none' } }
                            });
                        }
                    }
                    state.loading = false;
                });
        };
        const handleCancel = () => {
            state.visible = false;
        };
        // 获取数据表选项，每次选择完飞书文档后调用
        const getFsTableOptions = async () => {
            const query = {
                appToken: state.form.fsFileToken
            };
            const { success, moule } = await api.fsFileSyncTmplModel.findTablesByFileSyncTmplToken(query);
            if (success) {
                if (moule && moule.items && moule.items.length) {
                    state.fsTableOptions = [...moule.items];
                } else {
                    state.fsTableOptions = [];
                }
            }
        };
        const handleSelectChange = async (val, field) => {
            // 飞书文档
            if (field === 'fsFileName') {
                state.form.fsFileToken = val.docs_token;
                state.form.fsFileName = val.title;
                state.form.fsTableId = '';
                state.form.fsTableName = '';
                getFsTableOptions();
            }
            // 数据源系统
            else if (field === 'catalogCode') {
                state.form.catalogCode = val.catalogCode;
            }
            // 选择数据表
            else if (field === 'fsTableName') {
                const target = state.fsTableOptions.find((item) => item.name === val);
                if (target) {
                    state.form.fsTableId = target.table_id;
                } else {
                    state.form.fsTableId = '';
                }
            }
        };
        return {
            ruleFormRef,
            rules,
            ...toRefs(state),
            open,
            handleSave,
            handleCancel,
            handleSelectChange
        };
    }
});
</script>

<style scoped lang="less">
::v-deep(.section-wrap) {
    padding: 0 24px !important;
}
</style>